import {
  createEntityAdapter,
  createSlice,
  PayloadAction,
} from "@reduxjs/toolkit";
import { AppState } from "@store/index";

// 创建用于管理评论列表的实体适配器
const commentEntityAdapter = createEntityAdapter<ArticleComment>({
  selectId: (comment) => comment.com_id,
});

export const commentsSlice = createSlice({
  name: "comments",
  initialState: commentEntityAdapter.getInitialState(),
  reducers: {
    // 保存评论列表
    saveComments(state, action: PayloadAction<ArticleComment[]>) {
      commentEntityAdapter.addMany(state, action.payload);
    },
    // 清空评论列表
    clearComments(state) {
      commentEntityAdapter.removeAll(state);
    },
  },
});

export const commentsSelectors = commentEntityAdapter.getSelectors<AppState>(
  (state) => state.comments
);

export const { saveComments, clearComments } = commentsSlice.actions;
